﻿using System;
using System.Collections.Generic;
using Autofac;
using WindowsPhoneMVC.Navigation.Interfaces;

namespace WindowsPhoneMVC.Extensions.AutofacIntegration
{
    public class AutofacControllerFactory : IControllerFactory
    {
        private IContainer container;
        private readonly Dictionary<Controller, ILifetimeScope> lifetimeScopes;

        public AutofacControllerFactory()
        {
            lifetimeScopes = new Dictionary<Controller, ILifetimeScope>();
        }

        public T Create<T>() where T : Controller
        {
            var lifetimeScope = container.BeginLifetimeScope();
            var controller = lifetimeScope.Resolve<T>();

            lifetimeScopes.Add(controller, lifetimeScope);
            return controller;
        }

        public Controller Create(Type controllerType)
        {
            var lifetimeScope = container.BeginLifetimeScope();
            var controller = (Controller)lifetimeScope.Resolve(controllerType);

            lifetimeScopes.Add(controller, lifetimeScope);
            return controller;
        }

        public void SetContainer(IContainer container)
        {
            this.container = container;
        }

        public void Release(Controller controller)
        {
            if (!lifetimeScopes.ContainsKey(controller)) return;

            lifetimeScopes[controller].Dispose();
            lifetimeScopes.Remove(controller);
        }
    }
}
